<!-- Chat.vue -->
<template>
  <div>
    <div v-if="selectedUser">
      <h2>Chatting with {{ selectedUser }}</h2>
      <ul>
        <li v-for="message in messages" :key="message.id">
          <span v-if="message.sender === currentUser">{{ currentUser }}:</span>
          <span v-else>{{ message.sender }}:</span>
          {{ message.content }}
        </li>
      </ul>
      <form @submit.prevent="sendMessage">
        <input type="text" v-model="messageInput">
        <button>Send</button>
      </form>
    </div>
    <div v-else>
      <h2>Select a user to chat with</h2>
      <ul>
        <li v-for="user in users" :key="user">
          <button @click="selectUser(user)">{{ user }}</button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Stomp from "stompjs";
import SockJS from "sockjs-client";

export default {
  name: "Chat",

  data() {
    return {
      currentUser: "Alice",
      users: ["Bob", "Charlie", "Dave"],
      selectedUser: null,
      messageInput: "",
      messages: [],
      stompClient: null,
    };
  },

  methods: {
    connect() {
      const socket = new SockJS("/ws");
      this.stompClient = Stomp.over(socket);
      this.stompClient.connect({}, () => {
        this.stompClient.subscribe(
          `/user/${this.currentUser}/queue/messages`,
          (message) => {
            this.messages.push(JSON.parse(message.body));
          }
        );
      });
    },

    disconnect() {
      if (this.stompClient !== null) {
        this.stompClient.disconnect();
      }
    },

    selectUser(user) {
      this.selectedUser = user;
      this.connect();
    },

    sendMessage() {
      const chatMessage = {
        content: this.messageInput,
        sender: this.currentUser,
        receiver: this.selectedUser,
      };
      this.stompClient.send("/app/chat", {}, JSON.stringify(chatMessage));
      this.messageInput = "";
    },
  },

  beforeDestroy() {
    this.disconnect();
  },
};
</script>
